// 初始化树
const initTree = (data: any[], props: { label: string; value: string }) => {
  if (!Array.isArray(data)) {
    console.warn("data must be an array");
    return [];
  }
  let label = props.label || "label";
  let value = props.value || "value";
  for (let d of data) {
    d.label = d[label];
    d.value = d[value];
    if (d.children && d.children) {
      initTree(d.children, props);
    }
  }
  return data;
};

// 生成树
const createTree = (data: any[], index = 0, pid = "pid") => {
  let dataList = [] as any;
  if (!Array.isArray(data)) {
    return [];
  }
  dataList = data.filter((el) => {
    el.children = data.filter((el1) => el1[pid] == el.id);
    return el.pid == index;
  });

  return dataList;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export const handleTree = (
  data: any[],
  id?: string,
  parentId?: string,
  children?: string
) => {
  if (!Array.isArray(data)) {
    console.warn("data must be an array");
    return [];
  }
  const config = {
    id: id || "id",
    parentId: parentId || "parentId",
    childrenList: children || "children",
  };

  const childrenListMap: { [key: string]: any } = {};
  const nodeIds: { [key: string]: any } = {};
  const tree: any[] = [];

  for (const d of data) {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }

    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }
  // childrenListMap.parentId=[] || childrenListMap.parentId=[item]
  // nodeIds.id =item

  for (const d of data) {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }
  // 当父级id出现的时候 将当前项添加到tree数组中

  for (const t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o: { [key: string]: any }) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
        ? childrenListMap[o[config.id]]
        : [];
    }
    if (o[config.childrenList].length > 0) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }

  return tree;
};


interface TreeNode {
  [key: string]: any; // 支持动态键
}

const pathToTree = (pathArray: string[]): TreeNode[] => {
  const tree: TreeNode[] = [];

  for (const pathText of pathArray) {
    const parts = pathText.split('/').filter(Boolean); // 去掉空字符串
    let currentLevel = tree;
    for (const part of parts) {
      let existingNode = currentLevel.find(node => node.label === part);

      if (!existingNode) {
        existingNode = { label: part, value: part, children: [] };
        currentLevel.push(existingNode);
      }
      currentLevel = existingNode.children!;
    }
  }

  return tree;
};
 const treeData=(
    data: TreeNode[],
    tree: TreeNode[] = [],
    config: { id: string; parentId: string; children: string } = { id: 'id', parentId: 'pid', children: 'children' }
) => {

   const { id, parentId, children } = config;

   if (!tree.length) {
     // 初始化树根节点
     for (let i = 0; i < data.length; i++) {
       const value = data[i];
       if (value[parentId] === 0 || value[parentId] === '0' || value[parentId] == null) {
         tree.push(value);
         data.splice(i, 1);
         i--;
       }
     }
   }
   tree.forEach((node) => {
     for (let i = 0; i < data.length; i++) {
       const value = data[i];
       let element = value[parentId];
       if (element == node[id]) {
         if (!node[children]) {
           node[children] = [];
         }
         node[children].push(value);
         data.splice(i, 1);
         i--;
       }
     }
     // 递归构建子节点
     if (node[children] && node[children].length > 0) {
       treeData(data, node[children], config);
     }
   });

   return tree;
 }

const findLeafNodes =(nodes, leafNodes,key = 'id',children = 'children') => {
  if (nodes) {
    nodes.forEach(node => {
      if (node[children] && node[children].length > 0) {
        leafNodes.push(node[key]); // 如果没有子节点，则是叶子节点
      } else {
        // 如果有子节点，递归调用
        findLeafNodes(node.children, leafNodes);
      }
    });
  }
}

const sortTree = (tree)=> {
   tree = tree.sort((a,b)=>a.sort- b.sort)
  for (let t of tree) {
    if (t.children && t.children.length > 0) {
      sortTree(t.children)
    }
  }
}


const treeIds =(data, ids,pids,idKey = 'id')=> {
  if (!ids) {
    ids = []
  }
  if (!pids) {
    pids = []
  }

  if (data) {
    for (let i = 0; i < data.length; i++) {
      var d = data[i];
      if (d.checked) {
        ids.push(d[idKey])
      }
      if (d.data && d.data.length > 0) {
         treeIds(d.data, ids,pids,idKey)
        pids.push(d[idKey])
      }
    }
  }
  return {ids,pids}
}

const treeUtil = {
  initTree,
  createTree,
  handleTree,
  pathToTree,
  treeData,
  findLeafNodes,
  treeIds,
  sortTree
};

export default treeUtil;
